import { message } from 'antd';
import _ from 'lodash';
import type { IOrginDealElementOptions } from './type';

// 判断该用户是否有权限
export const havePermissions = (buttonType: string, buttonPermissions: any) => {
  const hasSave =
    buttonPermissions?.filter((item: any) => item.menuCode === buttonType)?.length > 0;
  if (!hasSave) {
    message.info('请联系管理员获取相关权限');
    return false;
  } else {
    return true;
  }
};

// 处理交易单元数据
export const getDealElementOptions = (data: IOrginDealElementOptions[]) => {
  const _settlemen: Record<string, any> = {};
  let dataObj: Record<string, any> = {};
  const modalData: any[] = data.map((m: IOrginDealElementOptions) => {
    const _children = m?.children?.map((item: IOrginDealElementOptions) => {
      const children = item?.children?.map((n: any) => ({
        ...n,
        title: n?.stationName,
        key: n?.stationId,
        parentKey: n?.groupId,
        regionId: n?.provinceId || '',
      }));
      dataObj = { ...dataObj, ..._.groupBy(children, 'value') };
      _settlemen[item?.groupId ? item?.groupId : ''] =
        _settlemen[item?.groupId ? item?.groupId : ''] || [];
      _settlemen[item?.groupId ? item?.groupId : ''] = [
        ..._settlemen[item?.groupId ? item?.groupId : ''],
        // @ts-ignore
        ...children,
      ];
      return {
        ...item,
        key: item?.groupId,
        title: item?.groupName || '',
        children,
        parentKey: m?.marketId,
      };
    });

    return { ...m, title: m?.marketName || '', children: _children, key: m?.marketId || '' };
  });
  return { modalData, value: _.flatten(Object.values(_settlemen)), dataObj };
};

// 数据保留小数位
export const ToFixed = (data: any, persion = 3) => {
  if (!data || isNaN(Number(data))) return data;
  const dot = String(data).indexOf('.');
  let num = Number(data);
  if (dot !== -1) {
    const dotCnt = String(data).substring(dot + 1, data.length);
    if (dotCnt.length > persion) {
      num = Number(Number(data).toFixed(persion));
    } else {
      num = Number(data);
    }
  }
  return num;
};
